<template>
  <div>

    <el-dropdown class="env-dropdown" trigger="hover" :teleported="false">
      <div class="env-select-button">
        <el-text truncated>{{showSelectEnvName?showSelectEnvName:'暂未配置环境'}}</el-text>
        <el-icon class="el-icon--right">
          <arrow-down/>
        </el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="item in interfaceEnvList"
                            @click="setInterfaceEnvId(item.id,item.env_name)">
            {{ item.env_name }}
          </el-dropdown-item>
          <el-dropdown-item disabled style="cursor: default">
            <el-button type="primary" link @click="openInterfaceEnvSettingDialog">查看环境配置</el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <el-dialog
        v-model="envSettingDialogVisible"
        title="环境配置"
        width="1000"
        append-to-body
        draggable
        :before-close="handleClose"
    >
      <div class="env-container">
        <el-card class="env-select">
          <el-scrollbar height="400px">
            <div v-for="item in interfaceEnvList" :key="item.id"
                 @click="selectEnv(item.id)"
                 :class="item.id === selectedEnvData.id?'select-item-selected':''"
                 class="select-item">{{ item.env_name }}
            </div>
          </el-scrollbar>
          <el-button type="primary" style="width: 100%" @click="addEnv">添加环境</el-button>
        </el-card>

        <el-card class="env-input-form">

          <el-table
              height="50px"
              :data="[{}]" :show-header="false" style="width: 100%">
            <el-table-column width="180">
              <template #default="scope">
                <el-text v-if="!isEditorEnvName">{{ selectedEnvData.env_name }}
                  <el-icon style="color: var(--el-color-primary)"
                           @click="focusEnvNameInput"
                           v-if="selectedEnvData.id && !isEditorEnvName">
                    <Edit/>
                  </el-icon>
                </el-text>
                <CustomInput v-model="selectedEnvData.env_name"
                             :id="'id'+selectedEnvData.id"
                             v-show="isEditorEnvName"
                             @blur="blurEnvNameInput"
                             placeholder="请输入环境名称" clearable></CustomInput>

              </template>
            </el-table-column>
            <el-table-column/>
            <el-table-column width="200">
              <template #default="scope">
                <div class="flx-justify-end">
                  <el-button :icon="Plus" circle
                             v-show="selectedEnvData.id"
                             @click="addEnvData"/>
                  <!--                  <el-button :icon="Edit" @click="" circle/>-->
                  <el-button :icon="Delete" circle
                             v-show="selectedEnvData.id"
                             @click="deleteAllEnvData"/>
                  <el-tooltip effect="light" content="说明文档" placement="top">
                    <el-button :icon="InfoFilled" circle @click=""/>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-table :data="selectedEnvData.env_value"
                    border :show-header="false"
                    height="320px"
                    style="width: 100%">
            <el-table-column label="key">
              <template #default="scope">
                <CustomInput v-model="scope.row.key" placeholder="请输入key" clearable></CustomInput>
              </template>
            </el-table-column>
            <el-table-column label="value">
              <template #default="scope">
                <CustomInput v-model="scope.row.value" placeholder="请输入value" clearable></CustomInput>
              </template>
            </el-table-column>
            <el-table-column label="description">
              <template #default="scope">
                <CustomInput v-model="scope.row.description" placeholder="请输入描述" clearable></CustomInput>
              </template>
            </el-table-column>

            <!--                 form-data,x-www-form-urlencoded 数据操作列 -->
            <el-table-column width="100">
              <template #default="scope">
                <div class="operation-column">
                  <el-switch
                      v-model="scope.row.enable"
                      inline-prompt
                      :active-icon="Check"
                      :inactive-icon="Close"
                  />
                  <el-button size="small"
                             style="margin-left: 10px"
                             @click="deleteEnvData(scope.row.id)"
                             :icon="Delete" circle/>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-button type="primary" class="saveEnvSetting"
                     :loading="commitLoading"
                     @click="saveEnvSetting">保存配置
          </el-button>

        </el-card>

      </div>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="envSettingDialogVisible = false">关闭</el-button>
        </div>
      </template>

    </el-dialog>
  </div>

</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";

import {
  Delete,
  ArrowDown,
  Check,
  Close, Plus, Edit, InfoFilled
} from "@element-plus/icons-vue";
import {storeToRefs} from "pinia";
import CustomInput from '@/components/CustomInput/index.vue'
import {getInterfaceEnvApi, postInterfaceEnvApi} from "@/api/modules/interface/interface.js";
import {useInterfaceEnvSettingStore} from "@/stores/modules/interface/interfaceEnvSetting.js";
import {getGuidApi} from "@/api/modules/system/common.js";
import {useTimestamp} from '@vueuse/core'
import {useProjectStore} from "@/stores/modules/project/project.js";
import {deepCopy} from "@/utils/index.js";

const timeStamp = useTimestamp()

const interfaceEnvSettingStore = useInterfaceEnvSettingStore()
const projectStore = useProjectStore()


const {interfaceEnvList} = storeToRefs(interfaceEnvSettingStore)
const {currentProject, currentProjectId} = storeToRefs(projectStore)

const props = defineProps({
  envId: {
    type: String,
    default: ""
  }
})

const emits = defineEmits(["update:envId"])

const showSelectEnvName = ref("")

const setInterfaceEnvId = (env_id,env_name) => {
  emits("update:envId", env_id)
  showSelectEnvName.value = env_name
}


const envSettingDialogVisible = ref(false)

const openInterfaceEnvSettingDialog = () => {
  envSettingDialogVisible.value = true;
  // 查询当前选中的环境数据
  if (props.envId) {
    getInterfaceEnvApi(props.envId).then(res => {
      selectedEnvData.value = res
    })
  }
}

const handleClose = (done) => {
  done()
}

onMounted(() => {
  interfaceEnvSettingStore.getInterfaceEnvList()
})


// 单个环境的变量数据
const selectedEnvData = ref({
  id: "",
  env_name: "",
  env_value: []
})

const isEditorEnvName = ref(false)

const focusEnvNameInput = (id) => {
  isEditorEnvName.value = true;
  nextTick(() => {
    setTimeout(() => {
      document.querySelector("#" + "id" + id).focus()
    }, 10)
  })
}

const blurEnvNameInput = () => {
  isEditorEnvName.value = false;
}


// 添加环境
const addEnv = () => {
  getGuidApi().then(res => {

    let envData = {
      id: res.data,
      env_name: "env_name",
      env_value: [{
        id: timeStamp.value,
        key: "",
        value: "",
        value_type: "",
        description: "",
        enable: true
      }],
      project: currentProjectId.value
    }

    interfaceEnvList.value.push(envData);
    selectedEnvData.value = envData
  })
}

// 点击选择环境
const selectEnv = (id) => {
  interfaceEnvList.value.forEach(item => {
    if (item.id === id) {
      // selectedEnvData.value = deepCopy(item) // 深拷贝问题，后续解决
      selectedEnvData.value = item
    }
  })
}

// 添加环境变量数据
const addEnvData = () => {
  selectedEnvData.value.env_value.push(
      {
        id: timeStamp.value,
        key: "",
        value: "",
        value_type: "",
        description: "",
        enable: true
      }
  )
}

const deleteAllEnvData = () => {
  selectedEnvData.value.env_value = []
}


// 删除环境变量数据
const deleteEnvData = (id) => {
  selectedEnvData.value.env_value.forEach((item, index) => {
    if (item.id === id) {
      console.log(item, index)
      selectedEnvData.value.env_value.splice(index, 1)
    }
  })
}


let commitLoading = ref(false)
const saveEnvSetting = () => {
  commitLoading.value = true
  postInterfaceEnvApi(selectedEnvData.value).then(res => {
    console.log(res)
    commitLoading.value = false
  }).catch(reason => {
    commitLoading.value = false
  })

  // 保存成功后再查一次数据
  interfaceEnvSettingStore.getInterfaceEnvList()
  // envSettingDialogVisible.value = false
}


</script>

<style scoped lang="scss">
.env-container {
  display: flex;

  .env-select {
    width: 250px;
    margin-right: 10px;

    :deep(.el-card__body) {
      padding: 0 !important;
    }

    .select-item {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 50px;
      margin: 10px;
      text-align: center;
      border-radius: 4px;
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
      cursor: pointer;

      &:hover {
        background: var(--el-color-primary-light-5);
      }
    }

    .select-item-selected {
      background: var(--el-color-primary-light-5);
    }
  }


  .env-input-form {
    width: 100%;
    position: relative;

    .saveEnvSetting {
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }

}

.el-overlay-dialog {
  overflow: inherit !important;
}
</style>
